package com.newear.util;

import android.app.Activity;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.media.MediaMetadataRetriever;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.Looper;
import android.preference.PreferenceManager;
import android.provider.MediaStore;
import android.support.v4.util.ArrayMap;
import android.telephony.TelephonyManager;
import android.util.Base64;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.newear.MyApplication;
import com.newear.activity.HappyLoginActivity;
import com.newear.base.glide.GlideUtil;
import com.newear.bean.CustomerInfo;
import com.newear.constant.IntentForResultCode;
import com.newear.constant.RequireParams;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.Method;
import java.net.NetworkInterface;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;

/**
 * 硬件的一些配置
 * Created by josan_tang on 2016/07/18.
 */
public class HardWare {
    private static final String TAG = "HardWare";
    private static String udid = "";

    /**
     * 屏幕大小
     */
    private static int screenWidth = 0;
    private static int screenHeight = 0;
    private static int densityDpi = 0;
    // 保存Activity
    public static List<Activity> ACTIIVTYS = new ArrayList<>();

    /**
     * 检查是否存在SDcard
     *
     * @return
     */
    public static boolean hasSdcard() {
        String state = Environment.getExternalStorageState();
        if (state.equals(Environment.MEDIA_MOUNTED)) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 关闭软键盘
     *
     * @param context
     * @param view
     */
    public static void closeKeyBoard(Context context, View view) {
        InputMethodManager inputMethodManager = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
        inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
    }

    /**
     * 得到屏幕大小、分辨率
     */
    private static void getScreenSize(Context appCon) {
        DisplayMetrics metrice = new DisplayMetrics();
        WindowManager manager = (WindowManager) appCon.getSystemService(Context.WINDOW_SERVICE);
        manager.getDefaultDisplay().getMetrics(metrice);
        screenWidth = metrice.widthPixels;
        screenHeight = metrice.heightPixels;
        densityDpi = metrice.densityDpi;
    }

    /**
     * 得到屏幕宽度
     *
     * @param appCon
     * @return
     */
    public static int getScreenWidth(Context appCon) {
        if (screenWidth == 0 && appCon != null) {
            getScreenSize(appCon);
        }
        return screenWidth;
    }

    /**
     * 设置屏幕宽度
     *
     * @param width
     */
    public static void setScreenWidth(int width) {
        screenWidth = width;
    }

    /**
     * 得到屏幕高度
     *
     * @param appCon
     * @return
     */
    public static int getScreenHeight(Context appCon) {
        if (screenHeight == 0 && appCon != null) {
            getScreenSize(appCon);
        }
        return screenHeight;
    }

    /**
     * 设置屏幕高度
     *
     * @param height
     */
    public static void setScreenHeight(int height) {
        screenHeight = height;
    }

    /**
     * 得到屏幕分辨率
     *
     * @param appCon
     * @return
     */
    public static int getDensityDpi(Context appCon) {
        if (densityDpi == 0 && appCon != null) {
            getScreenSize(appCon);
        }
        return densityDpi;
    }

    /**
     * 得到缩放比例
     *
     * @param screenWidthRatio
     * @param HeightWidthRatio Height/Width
     * @return
     */
    public static int[] getScale(Context context, double screenWidthRatio, double HeightWidthRatio) {
        int width = (int) (getScreenWidth(context) * screenWidthRatio);
        int height = (int) (width * HeightWidthRatio);
        return new int[]{width, height};
    }

    /**
     * 设置视图布局参数
     *
     * @param view
     * @param screenWidthRatio 控件宽度 与 屏幕宽度 之比
     * @param HeightWidthRatio 控件高度 与 控件宽度 之比。
     *                         大于1，宽 < 高；小于1， 宽 > 高。
     *                         eg:HardWare.setViewLayoutParams(img_head, 150 / 640.0, 1.0);
     */
    public static void setViewLayoutParams(Context context, View view, double screenWidthRatio, double HeightWidthRatio) {
        if (view != null) {
            int[] scale = getScale(context, screenWidthRatio, HeightWidthRatio);
            //MyLogger.v("宽" + scale[0] + "高：" + scale[1]);
            view.getLayoutParams().width = scale[0];
            view.getLayoutParams().height = scale[1];
        }
    }

    /**
     * 判断当前是否有网络
     *
     * @param appContext
     * @return
     */
    public static boolean isNetworkAvailable(Context appContext) {
        ConnectivityManager connectivityManager = (ConnectivityManager) appContext.getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connectivityManager == null) {
            return false;
        } else {
            NetworkInfo[] networkInfos = connectivityManager.getAllNetworkInfo();
            if (networkInfos != null && networkInfos.length > 0) {
                for (int i = 0; i < networkInfos.length; i++) {
                    if (networkInfos[i].getState() == NetworkInfo.State.CONNECTED) {
                        return true;
                    }
                }
            }
        }
        return false;
    }

    /**
     * 解除资源
     * 一般在onDestroy里调用
     *
     * @param view
     */
    public static void unbindDrawables(View view) {
        if (view == null) {
            return;
        }
        if (view.getBackground() != null) {
            view.getBackground().setCallback(null);
        }

        if (view instanceof ViewGroup) {
            int childCount = ((ViewGroup) view).getChildCount();
            for (int i = 0; i < childCount; i++) {
                unbindDrawables(((ViewGroup) view).getChildAt(i));
            }
            try {
                ((ViewGroup) view).removeAllViews();
            } catch (Exception e) {

            }
        }
    }

    public static ArrayMap<String, String> getBaseParams(Context appContext, boolean isKeepSign) {
        return getBaseParams(appContext, "", isKeepSign);
    }

    /**
     * 得到请求基础数据
     * National时，cityId=999
     *
     * @return
     */
    public static ArrayMap<String, String> getBaseParams(Context appContext, String cityId, boolean isKeepSign) {
        ArrayMap<String, String> baseParams = new ArrayMap<String, String>();
       /* baseParams.put("os", MyConstant.OS);    //设备类型-android
        baseParams.put(RequireParams.VERSION, MyConstant.VERSION);  //版本号

        String udid = HardWare.getUdid(appContext); //设备id
        if (Validator.isEffective(udid)) {
            baseParams.put(RequireParams.DEVICE_ID, udid);
        }*/
        //token
        String token = MySharedPreferences.getInstance().getToken(appContext);
        if (Validator.isEffective(token) && isKeepSign) {
            baseParams.put(RequireParams.TOKEN, token);
        }
        return baseParams;
    }

    /**
     * 得到请求基础数据
     *
     * @return
     */
    public static ArrayMap<String, String> getBaseParams(Context appContext) {
        return getBaseParams(appContext, "", true);
    }

    /**
     * 得到请求基础数据
     *
     * @return
     */
    public static ArrayMap<String, String> getBaseParams(Context appContext, String cityId) {
        return getBaseParams(appContext, cityId, true);
    }


    /**
     * 根据uri得到照片地址，这是目前可用的方法
     *
     * @param context
     * @param avatarUri
     * @return
     */
    public static String getFilePathByUri(Context context, Uri avatarUri) {
        String avatarPath = "";
        if (avatarUri.toString().startsWith("file")) { // file://
            avatarPath = avatarUri.toString().substring(6);
        } else if (Build.VERSION.SDK_INT >= 19) {
            avatarPath = HardWare.getPath(context, avatarUri);
        } else if (avatarUri.toString().startsWith("content")) {
            Cursor cursor = context.getContentResolver().query(avatarUri, null, null, null, null);
            if (cursor != null) {
                cursor.moveToFirst();
                // String imgNo = cursor.getString(0); //图片编号
                avatarPath = cursor.getString(1); // 图片文件路径
                // String imgSize = cursor.getString(2); //图片大小
                // String imgName = cursor.getString(3); //图片文件名
                cursor.close();
            }
        } else {
            return null;
        }
        return avatarPath;
    }


    public static String getPath(final Context context, final Uri uri) {

        final boolean isKitKat = Build.VERSION.SDK_INT >= 19;

        boolean isDocumentUri = false;
        String documentId = "";
        isDocumentUri = invokeIsDocumentUri(context, uri);
        documentId = invokeGetDocumentId(uri);
        // DocumentProvider
        if (isKitKat && isDocumentUri) {
            // ExternalStorageProvider
            if (isExternalStorageDocument(uri)) {
                final String docId = documentId;
                final String[] split = docId.split(":");
                final String type = split[0];

                if ("primary".equalsIgnoreCase(type)) {
                    return Environment.getExternalStorageDirectory() + "/" + split[1];
                }

                // TODO handle non-primary volumes
            }
            // DownloadsProvider
            else if (isDownloadsDocument(uri)) {

                final String id = documentId;
                final Uri contentUri = ContentUris.withAppendedId(
                        Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));

                return getDataColumn(context, contentUri, null, null);
            }
            // MediaProvider
            else if (isMediaDocument(uri)) {
                final String docId = documentId;
                final String[] split = docId.split(":");
                final String type = split[0];

                Uri contentUri = null;
                if ("image".equals(type)) {
                    contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                } else if ("video".equals(type)) {
                    contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
                } else if ("audio".equals(type)) {
                    contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
                }

                final String selection = "_id=?";
                final String[] selectionArgs = new String[]{
                        split[1]
                };

                return getDataColumn(context, contentUri, selection, selectionArgs);
            }
        }
        // MediaStore (and general)
        else if ("content".equalsIgnoreCase(uri.getScheme())) {

            // Return the remote address
            if (isGooglePhotosUri(uri))
                return uri.getLastPathSegment();

            return getDataColumn(context, uri, null, null);
        }
        // File
        else if ("file".equalsIgnoreCase(uri.getScheme())) {
            return uri.getPath();
        }

        return null;
    }

    private static boolean invokeIsDocumentUri(Context context, Uri uri) {
        try {
            Class<?> ownerClass = Class.forName("android.provider.DocumentsContract");
            Method method = ownerClass.getMethod("isDocumentUri", android.content.Context.class, android.net.Uri.class);
            return (Boolean) (method.invoke(null, context, uri));
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
            return false;
        }
    }

    private static String invokeGetDocumentId(Uri uri) {
        try {
            Class<?> ownerClass = Class.forName("android.provider.DocumentsContract");
            Method method = ownerClass.getMethod("getDocumentId", android.net.Uri.class);
            return (String) (method.invoke(null, uri));
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
            return "";
        }
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is ExternalStorageProvider.
     */
    public static boolean isExternalStorageDocument(Uri uri) {
        return "com.android.externalstorage.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is DownloadsProvider.
     */
    public static boolean isDownloadsDocument(Uri uri) {
        return "com.android.providers.downloads.documents".equals(uri.getAuthority());
    }

    /**
     * Get the value of the data column for this Uri. This is useful for
     * MediaStore Uris, and other file-based ContentProviders.
     *
     * @param context       The context.
     * @param uri           The Uri to query.
     * @param selection     (Optional) Filter used in the query.
     * @param selectionArgs (Optional) Selection arguments used in the query.
     * @return The value of the _data column, which is typically a file path.
     */
    public static String getDataColumn(Context context, Uri uri, String selection,
                                       String[] selectionArgs) {

        Cursor cursor = null;
        final String column = "_data";
        final String[] projection = {
                column
        };

        try {
            cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
                    null);
            if (cursor != null && cursor.moveToFirst()) {
                final int index = cursor.getColumnIndexOrThrow(column);
                return cursor.getString(index);
            }
        } finally {
            if (cursor != null)
                cursor.close();
        }
        return null;
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is MediaProvider.
     */
    public static boolean isMediaDocument(Uri uri) {
        return "com.android.providers.media.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is Google Photos.
     */
    public static boolean isGooglePhotosUri(Uri uri) {
        return "com.google.android.apps.photos.content".equals(uri.getAuthority());
    }

    /**
     * 跳转到登陆页面
     *
     * @param activity
     */
    public static void gotoLogin(Activity activity) {
        Intent intent = new Intent(activity, HappyLoginActivity.class);
        activity.startActivityForResult(intent, IntentForResultCode.LOGIN_REQUESTCODE);
    }

    /**
     * 清除缓存
     *
     * @param appContext
     */
    public static void clearCache(final Context appContext) {
        MyLogger.i(TAG, "clearCache");
        /** 清理Glide缓存 **/
        GlideUtil.getInstance(appContext).clearImageAllCache();

        try {
            if (Looper.myLooper() == Looper.getMainLooper()) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        clear(appContext);
                    }
                }).start();
            } else {
                clear(appContext);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 真正的清理缓存
     *
     * @param appContext
     */
    private static void clear(Context appContext) {
    }

    /**
     * 根据Bitmap生成文件路径
     *
     * @param bm
     * @param path
     * @throws IOException
     */
    public static boolean getFilePathByBitmap(Bitmap bm, final String path) {
        try {
            File file = new File(path);
            if (file.exists()) {
                file.delete();
            }
            FileOutputStream out;
            out = new FileOutputStream(file);
            if (bm.compress(Bitmap.CompressFormat.PNG, 100, out)) {
                out.flush();
                out.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return true;
    }

    /**
     * 压缩图片到文件
     *
     * @param bmp
     * @param path
     */
    public static boolean compressBmpToFile(Bitmap bmp, String path) {
        File file = new File(path);
        if (file.exists()) {
            file.delete();
        }
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        int options = 80;//个人喜欢从80开始,
        bmp.compress(Bitmap.CompressFormat.JPEG, options, baos);
        while (baos.toByteArray().length / 1024 > 100) {
            baos.reset();
            options -= 10;
            bmp.compress(Bitmap.CompressFormat.JPEG, options, baos);
        }
        try {
            FileOutputStream fos = new FileOutputStream(file);
            fos.write(baos.toByteArray());
            fos.flush();
            fos.close();
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 保存图片到相册
     * @param context
     * @param bmp
     * @param path
     * @return
     */
    public static boolean savePhotoToAlbum(Context context, Bitmap bmp, String path, String fileName){
        File fileDir = new File(path);
        if (!fileDir.exists()) {
            fileDir.mkdirs();
        }
        File file = new File(path + fileName);
        if (file.exists()) {
            file.delete();
        }
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        int options = 80;//个人喜欢从80开始,
        bmp.compress(Bitmap.CompressFormat.JPEG, options, baos);
        while (baos.toByteArray().length / 1024 > 100) {
            baos.reset();
            options -= 10;
            bmp.compress(Bitmap.CompressFormat.JPEG, options, baos);
        }
        try {
            FileOutputStream fos = new FileOutputStream(file);
            fos.write(baos.toByteArray());
            fos.flush();
            fos.close();
           /* // 其次把文件插入到系统图库
            try {
                MediaStore.Images.Media.insertImage(context.getContentResolver(),
                        file.getAbsolutePath(), fileName, null);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }*/
            // 最后通知图库更新
            context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(file)));
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return true;
    }

    /**
     * 取得udid,如果有就给治，没有就返回null字符串
     *
     * @param con
     * @return
     */
    public static String getUdid(Context con) {
        if (Validator.checkUdidValid(udid) == false) {
            SharedPreferences sharepre = PreferenceManager.getDefaultSharedPreferences(con);
            udid = sharepre.getString("udid", "");
            if (Validator.checkUdidValid(udid) == false) {
                try {
                    TelephonyManager tm = (TelephonyManager) con.getSystemService(Context.TELEPHONY_SERVICE);
                    udid = tm.getDeviceId();
                } catch (Exception e) {
                    udid = "null";
                }

                if (Validator.checkUdidValid(udid) == true) {
                    SharedPreferences.Editor editor = sharepre.edit();
                    editor.putString("udid", udid);
                    editor.apply();
                }
            }
        }
        return udid;
    }

    /**
     * 图片进行Base64转码，便于上传
     *
     * @param path
     * @return
     */
    public static String base64Encode(String path) {
        //decode to bitmap
        Bitmap bitmap = BitmapFactory.decodeFile(path);
        MyLogger.d(TAG, "bitmap width: " + bitmap.getWidth() + " height: " + bitmap.getHeight());
        //convert to byte array
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
        byte[] bytes = baos.toByteArray();
        MyLogger.d(TAG, "bytes.size: " + bytes.length);
        //base64 encode
        byte[] encode = Base64.encode(bytes, Base64.DEFAULT);
        String encodeString = new String(encode);
        return encodeString;
    }

    /**
     * 图片进行Base64转码，便于上传
     *
     * @param bitmap
     * @return
     */
    public static String base64Encode(Bitmap bitmap) {
        if (bitmap == null) {
            return "";
        }
        MyLogger.d(TAG, "bitmap width: " + bitmap.getWidth() + " height: " + bitmap.getHeight());
        //convert to byte array
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
        byte[] bytes = baos.toByteArray();
        MyLogger.d(TAG, "bytes.size: " + bytes.length);
        //base64 encode
        byte[] encode = Base64.encode(bytes, Base64.DEFAULT);
        String encodeString = new String(encode);
        return encodeString;
    }


    /**
     * 图片压缩
     * Compress image by size, this will modify image width/height.
     * Used to get thumbnail
     *
     * @param image
     * @param pixelW target pixel of width
     * @param pixelH target pixel of height
     * @return
     */
    public static Bitmap compressBitmap(Bitmap image, float pixelW, float pixelH) {
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        image.compress(Bitmap.CompressFormat.JPEG, 100, os);
        if (os.toByteArray().length / 1024 > 1024) {//判断如果图片大于1M,进行压缩避免在生成图片（BitmapFactory.decodeStream）时溢出
            os.reset();//重置baos即清空baos
            image.compress(Bitmap.CompressFormat.JPEG, 50, os);//这里压缩50%，把压缩后的数据存放到baos中
        }
        ByteArrayInputStream is = new ByteArrayInputStream(os.toByteArray());
        BitmapFactory.Options newOpts = new BitmapFactory.Options();
        //开始读入图片，此时把options.inJustDecodeBounds 设回true了
        newOpts.inJustDecodeBounds = true;
        newOpts.inPreferredConfig = Bitmap.Config.RGB_565;
        newOpts.inJustDecodeBounds = false;
        int w = newOpts.outWidth;
        int h = newOpts.outHeight;
        float hh = pixelH;// 设置高度为240f时，可以明显看到图片缩小了
        float ww = pixelW;// 设置宽度为120f，可以明显看到图片缩小了
        //缩放比。由于是固定比例缩放，只用高或者宽其中一个数据进行计算即可
        int be = 1;//be=1表示不缩放
        if (w > h && w > ww) {//如果宽度大的话根据宽度固定大小缩放
            be = (int) (newOpts.outWidth / ww);
        } else if (w < h && h > hh) {//如果高度高的话根据宽度固定大小缩放
            be = (int) (newOpts.outHeight / hh);
        }
        if (be <= 0) be = 1;
        newOpts.inSampleSize = be;//设置缩放比例
        //重新读入图片，注意此时已经把options.inJustDecodeBounds 设回false了
        is = new ByteArrayInputStream(os.toByteArray());
        Bitmap bitmap = BitmapFactory.decodeStream(is, null, newOpts);
        //压缩好比例大小后再进行质量压缩
//      return compress(bitmap, maxSize); // 这里再进行质量压缩的意义不大，反而耗资源，删除
        return bitmap;
    }

    /**
     * 时间戳得到具体时间，unix时间，1970年开始
     * 比如1252639886-> 2009-11-09
     * MMMM dd，yyyy
     *
     * @param timestampString
     * @param formats
     * @return
     */
    public static String timeStamp2Date(String timestampString, String formats) {
        try {
            Long timestamp = Long.parseLong(timestampString) * 1000;
            String date = new java.text.SimpleDateFormat(formats, Locale.ENGLISH).format(new java.util.Date(timestamp));
            return date;
        } catch (Exception e) {
            return "";
        }
    }

    /**
     * 时间搓，不从1970差值
     * MMMM dd，yyyy
     *
     * @param timestampString
     * @param formats
     * @return
     */
    public static String timeMillis2Date(String timestampString, String formats) {
        try {
            Long timestamp = Long.parseLong(timestampString);
            String date = new java.text.SimpleDateFormat(formats).format(new java.util.Date(timestamp));
            return date;
        } catch (Exception e) {
            return "";
        }
    }

    //字符串转时间戳
    public static String getTime(String timeString) {
        String timeStamp = null;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date d;
        try {
            d = sdf.parse(timeString);
            long l = d.getTime();
            timeStamp = String.valueOf(l);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return timeStamp;
    }

    /**
     * 是否使用了VPN
     *
     * @return
     */
    public static boolean isVpnUsed() {
        try {
            Enumeration<NetworkInterface> niList = NetworkInterface.getNetworkInterfaces();
            if (niList != null) {
                for (NetworkInterface intf : Collections.list(niList)) {
                    if (!intf.isUp() || intf.getInterfaceAddresses().size() == 0) {
                        continue;
                    }
                    MyLogger.d(TAG, "isVpnUsed() NetworkInterface Name: " + intf.getName());
                    if ("tun0".equals(intf.getName()) || "ppp0".equals(intf.getName())) {
                        return true; // The VPN is up
                    }
                }
            }
        } catch (Throwable e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 得到当前时间
     *
     * @return
     */
    public static String getCurDate() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");
        String date = sdf.format(new java.util.Date());
        return date;
    }

    /**
     * 得到当前时间
     *
     * @return
     */
    public static String getCurDateStr() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm");
        String date = sdf.format(new java.util.Date());
        return date;
    }

    /**
     * 得到当前时间
     *
     * @return
     */
    public static String getCurDate2() {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String date = sdf.format(new java.util.Date());
        return date;
    }

    /**
     * 是否需要更新
     * @param nowVersion
     * @return
     */
    public static boolean needUpdateApk(String nowVersion) {
        int[] now = new int[3];
        int[] old = new int[3];
        if (!Validator.isEffective(nowVersion)) {
            return false;
        }
        try {
            String[] nowArr = nowVersion.split("\\.");
            if (nowArr != null && nowArr.length > 0) {  //现在的
                for (int i = 0; i < 3; i++) {
                    if (i < nowArr.length) {
                        now[i] = Integer.parseInt(nowArr[i]);
                    } else {
                        now[i] = 0;
                    }
                }
            }


            String oldVersion = MyConstant.VERSION;
            String[] oldArr = oldVersion.split("\\.");
            if (oldArr != null && oldArr.length > 0) {  //以前的
                for (int i = 0; i < 3; i++) {
                    if (i < oldArr.length) {
                        old[i] = Integer.parseInt(oldArr[i]);
                    } else {
                        old[i] = 0;
                    }
                }
            }

            MyLogger.i(TAG, "old:"+old[0] + old[1] + old[2] + "--now:" + now[0]+ now[1]+ now[2]);

            if (now[0] > old[0]) {
                return true;
            }else if (now[0] == old[0]) {
                if (now[1] > old[1]) {
                    return true;
                } else if (now[1] == old[1]) {
                    if (now[2] > old[2]) {
                        return true;
                    }
                }
            }

        } catch (Exception e) {
            return false;
        }
        return false;
    }


    /**
     * 将图片按照某个角度进行旋转
     *
     * @param bm     需要旋转的图片
     * @return 旋转后的图片
     */
    public static Bitmap rotateBitmap(Bitmap bm) {
        Bitmap returnBm = null;

        // 根据旋转角度，生成旋转矩阵
        Matrix matrix = new Matrix();

        if (android.os.Build.MODEL.contains("ONEPLUS A3010")) {
            matrix.postRotate(270);
        } else {
            matrix.postRotate(180);
        }
        matrix.postScale(-1, 1);
        try {
            // 将原始图片按照旋转矩阵进行旋转，并得到新的图片
            returnBm = Bitmap.createBitmap(bm, 0, 0, bm.getWidth(),
                    bm.getHeight(), matrix, true);
        } catch (OutOfMemoryError e) {
            e.printStackTrace();
        }
        if (returnBm == null) {
            returnBm = bm;
        }
        if (bm != returnBm) {
            bm.recycle();
        }
        return returnBm;
    }

    /**
     * 判断是否登陆了，根据token判断
     * @return
     */
    public static boolean isLogined(Context context) {
        String token= MySharedPreferences.getInstance().getToken(context);
        if (Validator.isEffective(token)) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 构造请求报告的json
     * @return
     */
    public static String getRequestReportJson() {
        JSONObject jsonObject = new JSONObject();
        CustomerInfo customerInfo = MyApplication.sCustomerInfo;
        if (customerInfo == null) {
            return null;
        }
        try {
            // 舌诊和面诊
            // todo
            /*jsonObject.put("face_result_id", 29);
            jsonObject.put("tongue_result_id", 10);*/
            jsonObject.put("face_result_id", customerInfo.faceId);
            jsonObject.put("tongue_result_id", customerInfo.tongueId);
            jsonObject.put("num", customerInfo.vipNum);

            // 个人信息
            JSONObject userInfoObj = new JSONObject();
            userInfoObj.put("age", customerInfo.ageGrade);
            userInfoObj.put("gender", customerInfo.sex);
            userInfoObj.put("pregnant", customerInfo.femaleStatu);
            jsonObject.put("user_info", userInfoObj);
            // 问诊
            // 单选和多选1在一个数组中
            JSONArray multiSelect1Arr = new JSONArray();
            int[] singleSelect = customerInfo.singleSelect;
            if (singleSelect != null && singleSelect.length > 0) {
                for (int i = 0; i < singleSelect.length; i++) {
                    JSONObject singleSelectObj = new JSONObject();
                    singleSelectObj.put("id", (i + 1) + "");
                    int selects = singleSelect[i];
                    JSONArray selectArr = new JSONArray();
                    if (selects == 1) {
                        selectArr.put("A");
                    } else {
                        selectArr.put("B");
                    }
                    singleSelectObj.put("answer", selectArr);
                    multiSelect1Arr.put(singleSelectObj);
                }
            }
            int multiStartIndex = multiSelect1Arr.length();
            int[] multiSelect1 = customerInfo.multiSelect1;
            if (multiSelect1 != null && multiSelect1.length > 0) {
                for (int i = 0; i < multiSelect1.length; i++) {
                    JSONObject multiSelect1Obj = new JSONObject();
                    multiSelect1Obj.put("id", (multiStartIndex + 1 + i) + "");
                    int selects = multiSelect1[i];
                    if (selects > 0) {
                        JSONArray selectArr = new JSONArray();
                        String selectStr = selects + "";
                        for (int j = 0; j < selectStr.length(); j++) {
                            char selectChar = (char) (Integer.parseInt(selectStr.charAt(j) + "") - 1 + 65);
                            selectArr.put(selectChar);
                        }
                        multiSelect1Obj.put("answer", selectArr);
                    }
                    multiSelect1Arr.put(multiSelect1Obj);
                }
                jsonObject.put("answers", multiSelect1Arr);
            }
            // 多选2
            int[] multiSelect2 = customerInfo.multiSelect2;
            if (multiSelect2 != null && multiSelect2.length > 0) {
                JSONArray multiSelect2Arr = new JSONArray();
                for (int i = 0; i < multiSelect2.length; i++) {
                    multiSelect2Arr.put(multiSelect2[i]);
                }
                jsonObject.put("med_recommend", multiSelect2Arr);
            }
            return jsonObject.toJSONString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 得到时间相关
     * @return
     */
    public static String[] getTime() {
        Calendar c = Calendar.getInstance();
        int mYear = c.get(Calendar.YEAR); // 获取当前年份
        int mMonth = c.get(Calendar.MONTH) + 1;// 获取当前月份
        int mDay = c.get(Calendar.DAY_OF_MONTH);// 获取当日期
        int mWay = c.get(Calendar.DAY_OF_WEEK);// 获取当前日期的星期
        int mHour = c.get(Calendar.HOUR_OF_DAY);//时
        int mMinute = c.get(Calendar.MINUTE);//分
        int amOrPm =c.get(Calendar.AM_PM);

        String[] result = new String[3];
        result[0] = "";
        if (amOrPm == Calendar.PM && mHour < 12) {
            mHour += 12;
        }
        if (mHour < 10) {
            result[0] += "0";
        }
        result[0] += mHour;
        result[0] += ":";
        if (mMinute < 10) {
            result[0] += "0";
        }
        result[0] += mMinute;
        String wayStr = "" + mWay;
        if("1".equals(wayStr)){
            wayStr ="天";
        }else if("2".equals(wayStr)){
            wayStr ="一";
        }else if("3".equals(wayStr)){
            wayStr ="二";
        }else if("4".equals(wayStr)){
            wayStr ="三";
        }else if("5".equals(wayStr)){
            wayStr ="四";
        }else if("6".equals(wayStr)){
            wayStr ="五";
        }else if("7".equals(wayStr)){
            wayStr ="六";
        }
        result[1] = "星期" + wayStr;
        result[2] = mYear + "年" + mMonth + "月" + mDay + "日";
        return result;
    }

    /**
     * 对正数排序，比如1324，排列后1234
     * @param number
     * @return
     */
    public static int getSort(int number) {
        if (number == 0) {
            return 0;
        }
        int result = 0;
        String numberStr = number + "";
        int[] numberArr = new int[numberStr.length()];
        for (int i = 0; i < numberStr.length(); i++) {
            numberArr[i] = Integer.parseInt(numberStr.charAt(i)+"");
        }
        Arrays.sort(numberArr);
        for (int i = 0; i < numberArr.length; i++) {
            result += (numberArr[i] * Math.pow(10, (numberArr.length - i - 1)));
        }
        return result;
    }

    public static void registerActivity(Activity activity) {
        if (!ACTIIVTYS.contains(activity)) {
            ACTIIVTYS.add(activity);
        }
    }

    public static void unregisterActivity(Activity activity) {
        if (ACTIIVTYS.contains(activity)) {
            ACTIIVTYS.remove(activity);
        }
    }

    public static void finishAllActivity() {
        if (ACTIIVTYS != null) {
            for (int i = 0; i < ACTIIVTYS.size(); i++) {
                ACTIIVTYS.get(i).finish();

            }
            ACTIIVTYS.clear();
        }
    }

    public static Bitmap getNetVideoBitmap(String videoUrl) {
        Bitmap bitmap = null;

        MediaMetadataRetriever retriever = new MediaMetadataRetriever();
        try {
            //根据url获取缩略图
            retriever.setDataSource(videoUrl, new HashMap());
            //获得第一帧图片
            bitmap = retriever.getFrameAtTime();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } finally {
            retriever.release();
        }
        return bitmap;
    }
}
